<!-- tool-set -->
<template>
    <div class="set-wrapper">

        <div class="left-tree">
            
            <div class="left-tree-top">
                 
                <el-dropdown 
                @command="editToolType"
                :hide-on-click="false">
                    <span class="el-dropdown-link">
                        工具类型<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="a">增加类型</el-dropdown-item>
                        <el-dropdown-item command="b">删除类型</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>   
            </div>
            <div 
            v-loading="treeLoading"
            element-loading-text="加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            class="left-tree-bottom">
                <el-tree 
                ref="popularTree"
                node-key="id"
                highlight-current
                :current-node-key="selectedId"
                :check-strictly="true"
                :expand-on-click-node="false"
                :data="treeData"
                default-expand-all 
                :props="defaultProps" 
                @node-click="handleNodeClick"></el-tree>
            </div>
        </div>

        <div class="right-content">
            <div class="top">
                <span 
                class="cat-title">
                    工具类别
                </span>

                <span 
                @click="handleClickAdd"
                class="btn">
                    新增
                </span>
            </div>

            <div class="tb">
                <el-table
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :data="tableData"
                height="100%"
                border
                style="width: 100%">

                     <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="100"
                    >
                    </el-table-column>

                    <el-table-column
                    label="名称"
                    prop="toolName"
                    align="center"
                    >
                    </el-table-column>

                    <el-table-column
                    label="规格"
                    prop="toolSpec"
                    align="center"
                    >
                    </el-table-column>

                    <el-table-column
                    label="状态"
                    prop="deleted"
                    align="center"
                    >
                        <template slot-scope="scope">
                            {{scope.row.deleted == 0 ? '可用' : '停用'}}
                        </template> 
                    </el-table-column>

                    <el-table-column
                    label="ID"
                    prop="id"
                    align="center"
                    >
                        
                    </el-table-column>

                    <el-table-column
                    label="操作"
                    align="center"
                    width="340"
                    >
                        <template slot-scope="scope">
                            <el-button @click="handleClick(scope.row)" type="text" size="small">修改</el-button>
                            <el-button @click="handleRemove(scope.row)" type="text" size="small">删除</el-button>
                            <!-- <el-button @click="handleMatin(scope.row)" type="text" size="small">维护ID</el-button> -->
                        </template> 
                    </el-table-column>

                </el-table>
            </div>
        </div>
    
        

        <!-- 增加工具对话框 -->
        <el-dialog 
        width="84%"
        :title="dialogTitle" 
        :close-on-click-modal="false"
        :visible.sync="dialogFormVisible">
            <el-form ref="form" :model="form" label-width="140px">
                <el-form-item label="工具类型">
                    <treeselect
                    placeholder="请选择工具类型"
                    :options="treeData"
                    v-model="form.type"
                    :normalizer="normalizer"
                    />
                </el-form-item>
                <el-form-item label="工具名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="工具规格">
                    <el-input v-model="form.g"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select
                    clearable 
                    v-model="form.state" 
                    placeholder="请选择状态">
                        <el-option label="可用" :value="0"></el-option>
                        <el-option label="停用" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="工具编码" style="position: relative">
                    <el-input
                    type="textarea"
                    placeholder="请录入工具编码"
                    v-model="form.toolCode">
                    </el-input>
                    <span class="in-code" @click="handleInCode">{{btn2val}}</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button 
                :loading="adding1"
                type="primary" 
                @click="handleAddNew">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 增加工具类型对话框 -->
        <el-dialog 
        width="84%"
        :title="dialogTitle1" 
        :close-on-click-modal="false"
        :visible.sync="dialogFormVisible1">
            <el-form ref="form1" :model="form1" label-width="140px">
                <el-form-item label="父级选择">
                    <treeselect
                    placeholder="请选择父级节点"
                    :options="treeData1"
                    @select="changeParentNode"
                    v-model="form1.parentId"
                    :normalizer="normalizer"
                    />
                </el-form-item>
                <el-form-item label="类型名称">
                    <el-input v-model="form1.typeName"></el-input>
                </el-form-item>
                
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取 消</el-button>
                <el-button
                :loading="adding2" 
                type="primary" 
                @click="handleAddNewType">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除类型对话框 -->
        <el-dialog 
        width="84%"
        title="删除" 
        :close-on-click-modal="false"
        :visible.sync="dialogFormVisible2">
            <el-form ref="form2" :model="form1" label-width="140px">
                <el-form-item label="工具类型">
                    <treeselect
                    placeholder="请选择工具类型"
                    :options="treeData"
                    v-model="form2.type"
                    :normalizer="normalizer"
                    />
                </el-form-item>
                
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button
                :loading="adding3" 
                type="primary" 
                @click="delTempName">删除</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import {
    requestToolList,
    requestToolTree,
    addNewTools,
    addNewToolType,
    delTools,
    editTools,
    delToolType
} from '@/apis';
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    name: 'tool-set',
    components: {
        Treeselect 
    },
    data () {    
        return {
            categoryLevel: 0,
            btn2val: '开始清点',
            adding1: false,
            adding2: false,
            adding3: false,
            dialogTitle: '新增',
            dialogFormVisible: false,
            dialogFormVisible2: false,
            dialogTitle1: '增加工具类型',
            dialogFormVisible1: false,
            // 表格数据
            /* {
                "id": "CD9CA9CCE64D4D358F2A469D024AC33F",
                "toolName": "钳子",
                "toolSpec": "小号",
                "toolCode": "E28068940000401928C6E9AD",
                "categoryId": "3158695265B641CE9FC19A6FF99A28AB",
                "belongDept": 99,
                "operateTime": "2021-09-16 15:31:43",
                "operateUser": "super",
                "deleted": 0
            } */
            tableData: [], 
            tableId: null,
            // table - loading
            loading: false,
            // 页码
            currentPage: 1,
            // 每页显示数量
            pageSize: 10,
            // 列表总数量
            totalNum: 400,
            // form
            form: {
                type: null,
                name: null,
                g: null,
                state: null,
                toolCode: null
            },
            form1: {
                typeName: null
            },
            form2: {
                type: null
            },
            /* {
                "id": "3158695265B641CE9FC19A6FF99A28AB",
                "categoryName": "常用工具2",
                "categoryLevel": 1,
                "sortNo": null,
                "parentId": "-1",
                "belongDept": 99,
                "children": [{
                    "id": "4158695265B641CE9FC19A6FF99A28AB",
                    "categoryName": "常用工具2-1",
                    "categoryLevel": 2,
                    "sortNo": null,
                    "parentId": "-1",
                    "belongDept": 99,
                }]
            } */
            treeData: [],
            treeData1: [],
            
            defaultProps: {
                children: 'children',
                label: 'categoryName'
            },
            treeLoading: false,
            selectedId: null,
            // 是否删除 1 删除 0 正常 ,
            status: [{
                label: '停用',
                value: 1
            },{
                label: '可用',
                value: 0
            }],
            normalizer(node) {
                return {
                    id: node.id,
                    label: node.categoryName,
                    children: node.children,
                }
            },
            timer: null,
            toolCodeAry: []
        }
    },
    watch: {
        // 对话框关闭之后需清空数据
        dialogFormVisible (newVal, oldVal) {
            if (!newVal) {
                this.form = this.$options.data().form;
                this.toolCodeAry = [];
                this.stopCheck();
            }
        },
        // 对话框关闭之后需清空数据
        dialogFormVisible1 (newVal, oldVal) {
            if (!newVal) {
                this.form1 = this.$options.data().form1;
            }
        },
        // 对话框关闭之后需清空数据
        dialogFormVisible2 (newVal, oldVal) {
            if (!newVal) {
                this.form2 = this.$options.data().form2;
            }
        },
        toolCodeAry: {
            deep: true,
            handler (newVal, oldVal) {
                this.form.toolCode = newVal.join(', ');
            }
        } 
    },
    computed: {
        url1 () {
            return `https://localhost:8862`
            //return '/local'
        }
    },
    methods: {
        
        // 点击删除模板名称
        delTempName () {
            this.$confirm('确认删除吗？')
            .then(_ => {
                console.log(_)
                this.removeToolType();
            })
        },

        // 删除 - 工具名称
        async removeToolType () {
            try {
                this.adding3 = true;
                let res = await delToolType(this.form2.type);
                console.log('删除 - 工具类型', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                   this.$message({
                        type: 'success',
                        message: `${msg}`
                    })  
                    this.getTreeData();   
                    this.adding3 = false;
                    this.dialogFormVisible2 = false;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.adding3 = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.adding3 = false;
                }
            } catch(e) {
                this.adding3 = false;
                console.log('删除 - 工具类型',e)
            }
        },

        // 请求设置列表
        async getDevSetList () {
            try {
                if (!this.selectedId) return;
                this.loading = true;
                let res = await requestToolList(this.selectedId);
                console.log('请求设置列表', res);
                let {
                    code,
                    msg,
                    data,
                    total
                } = res.data;
                if (code == 200) {
                    
                    this.tableData = data;
                    this.loading = false;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.loading = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.loading = false;
                }
            } catch(e) {
                this.loading = false;
                console.log('请求设置列表',e)
            }
        },

        // 请求树形菜单
        async getTreeData () {
            try {
                this.treeLoading = true;
                //let deptId = 99;
                let deptId = window.localStorage.getItem('organizationId'); 
                let res = await requestToolTree(deptId);
                console.log('请求树形菜单', res);
                let {
                    code,
                    msg,
                    data
                } = res.data;
                if (code == 200) {
                    // 
                    this.treeData1 = [data];
                    this.treeData = data.children;
                    this.selectedId = data.children.length != 0 ? data.children[0].id : null;
                    this.$nextTick(function () {
                        this.$refs.popularTree.setCurrentKey(this.selectedId)
                    })
                    this.getDevSetList();
                    this.treeLoading = false;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.treeLoading = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.treeLoading = false;
                }
            } catch(e) {
                this.treeLoading = false;
                console.log('请求树形菜单',e)
            }
        },

        // 点击树形节点
        handleNodeClick (node) {
            //console.log('点击树形节点', node);
            this.selectedId = node.id;
            this.getDevSetList();
        },

        // 新增 - 工具
        async addNewTool () {
            try {
                this.adding1 = true;
                let id = window.localStorage.getItem('organizationId');
                let params = {
                    belongDept: id,// 99
                    categoryId: this.form.type,
                    deleted: this.form.state,
                    toolCode: this.form.toolCode,
                    toolName:  this.form.name,
                    toolSpec: this.form.g
                }
                let res = await addNewTools(params);
                console.log('新增 - 工具', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.getDevSetList();    
                    this.adding1 = false;
                    this.$message({
                        type: 'success',
                        message: `${msg}`
                    })
                    this.dialogFormVisible = false;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.adding1 = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.adding1 = false;
                }
            } catch(e) {
                this.adding1 = false;
                console.log('新增 - 工具',e)
            }
        },

        // 编辑 - 工具
        async editTool () {
            try {
                this.adding1 = true;
                let id = window.localStorage.getItem('organizationId');
                let params = {
                    id: this.tableId,
                    belongDept: id,// 99
                    categoryId: this.form.type,
                    deleted: this.form.state,
                    toolCode: this.form.toolCode,
                    toolName:  this.form.name,
                    toolSpec: this.form.g
                }
                let res = await editTools(params);
                console.log('编辑 - 工具', res);
                let {
                    code,
                    msg,
                    
                } = res.data;
                if (code == 200) {
                    this.getDevSetList(); 
                    this.$message({
                        type: 'success',
                        message: `${msg}`
                    })  
                    this.dialogFormVisible = false; 
                    this.adding1 = false;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.adding1 = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.adding1 = false;
                }
            } catch(e) {
                this.adding1 = false;
                console.log('编辑 - 工具',e)
            }
        },

        // 删除 - 工具
        async delTool (id) {
            try {
                let res = await delTools(id);
                console.log('删除 - 工具', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.getDevSetList();
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                }
            } catch(e) {
                console.log('删除 - 工具',e)
            }
        },

        // 新增 - 工具类型
        async addToolType () {
            try {
                this.adding2 = true;
                let deptId = window.localStorage.getItem('organizationId');
                let params = {
                    categoryLevel: this.categoryLevel,
                    "belongDept": deptId,// 99
                    "categoryName": this.form1.typeName,                      
                    "parentId": this.form1.parentId
                }
                let res = await addNewToolType(params);
                console.log('新增 - 工具类型', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.$message({
                        type: 'success',
                        message: `${msg}`
                    })  
                    this.getTreeData();
                    this.dialogFormVisible1 = false;  
                    this.adding2 = false;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.adding2 = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    });
                    this.adding2 = false;
                }
            } catch(e) {
                this.adding2 = false;
                console.log('新增 - 工具类型',e)
            }
        },

        // 点击新增按钮
        handleClickAdd () {
            this.dialogFormVisible = true;
        },

        // 点击修改
        handleClick (row) {
            console.log(row);
            this.tableId = row.id;
            this.dialogTitle = '修改';
            this.dialogFormVisible = true;
            this.form.type = row.categoryId;
            this.form.name = row.toolName;
            this.form.g = row.toolSpec;
            this.form.state = row.deleted;
            this.form.toolCode = row.toolCode;
        },

        // 点击删除
        handleRemove (row) {
            // console.log(row);
            let id = row.id;
            this.$confirm('确认删除吗？')
            .then(_ => {
                console.log(_);
                this.delTool(id);
            })
            .catch(_ => {
                console.log(_);
            });
        }, 

        // 点击维护
        handleMatin (row) {
            console.log(row);
        }, 

        // 对话框－点击添加按钮
        handleAddNew () {
            if (this.dialogTitle == '新增') {
                this.addNewTool();
            } else if (this.dialogTitle == '修改') {
                this.editTool();
            }
        },

        // 对话框－点击添加按钮

        // 点击工具类型内部的增加或者是删除
        editToolType (type) {
            if (type == 'a') {
                this.dialogFormVisible1 = true    
            } else if (type == 'b') {
                this.dialogFormVisible2 = true    
            } 
        },

        // 类型对话框－－点击确定
        handleAddNewType () {
            this.addToolType();
        },

        // 点击录入code
        handleInCode () {
            if (this.btn2val == '开始清点' || this.btn2val == '重新清点') {
                this.startCheck();
            } else if (this.btn2val == '结束清点') {
                this.stopCheck();
            }
        },

        // 开始清点
        startCheck () {
            this.$axios.get(this.url1 + '/startCheck').then(res => {
                console.log('清点数据', res);
                this.btn2val = '结束清点';
                this.timer && window.clearInterval(this.timer);
                this.timer = null;
                this.timer = setInterval(() => {
                    this.recevieData();
                }, 1000)
            })
        },

        // 获取清点数据
        recevieData () {
            this.$axios.get(this.url1 + '/getTagData').then(res => {
                let devs = res.data;
                this.toolCodeAry = Array.from(new Set([...this.toolCodeAry, ...devs]))
            })
        },

        // 结束清点
        stopCheck () {
            this.$axios.get(this.url1 + '/stopCheck').then(res => {
                console.log('结束清点', res);
                this.timer && window.clearInterval(this.timer);
                this.timer = null;
                this.btn2val = '重新清点';
                this.dis1 = false;
            })
        },

        // 选择父类节点
        changeParentNode (node) {
            console.log('node -----',node)
            this.categoryLevel = node.categoryLevel + 1;
        }
    },
    created () {
        this.getTreeData();
    }
}
</script>
<style lang='scss'>
.left-tree {
    width: 16%;
    height: 100%;
    overflow: auto;
    float: left;
    margin-right: 1%;

    &-top {
        width: 100%;
        height: 44px;
        padding-bottom: 20px;
        font-size: 24px;
        line-height: 44px;
        color: #fff;
    }

    &-bottom {
        width: 100%;
        height: calc(100% - 64px);
        box-sizing: border-box;
        border: 1px solid #43587A;
        background: #202E45;
        overflow: auto;
        min-width: 310px;
        
    }
}

.right-content {
    width: 83%;
    height: 100%;
    float: left;

    .top {
        height: 44px;
        padding-bottom: 20px;
        overflow: hidden;

        .btn {
            width: 156px;
            height: 44px;
            color: #fff;
            font-size: 24px;
            line-height: 44px;
            background: #2683FF;
            border-radius: 4px;
            cursor: pointer;
            float: right;
            text-align: center;
        }

        .cat-title {
            width: 250px;
            height: 44px;
            line-height: 44px;
            font-size: 24px;
            color: #fff;
            float: left;
        }
    }

    .tb {
        height: calc(100% - 64px);
        
    }
}

.in-code {
    position: absolute;
    font-size: 24px;
    right: -120px;
    top: 13px;
    color: #fff;
    cursor: pointer;

    &:hover {
        color: #66b1ff;
    }
}
</style>